package edu.wit.controller;

import edu.wit.common.api.model.LoginUser;
import edu.wit.common.constant.CacheConstants;
import edu.wit.common.core.domain.R;
import edu.wit.common.core.web.BaseController;
import edu.wit.common.core.web.page.TableDataInfo;
import edu.wit.common.redis.service.RedisService;
import edu.wit.common.security.service.TokenService;
import edu.wit.common.utils.StringUtils;
import edu.wit.entity.vo.SysUserOnline;
import edu.wit.form.LoginBody;
import edu.wit.service.ISysUserOnlineService;
import edu.wit.service.SysLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * token 控制
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/admin/auth")
@Api("登录认证模块")
public class TokenController extends BaseController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private ISysUserOnlineService userOnlineService;

    @ApiOperation(value = "登录",httpMethod = "POST")
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());

        // 获取登录token
        return R.ok(tokenService.createToken(userInfo),"登陆成功");
    }

    @ApiOperation("退出登录")
    @DeleteMapping("logout")
    public R<?> logout() {
        LoginUser loginUser = tokenService.getLoginUserByToken();
        if (StringUtils.isNotNull(loginUser)) {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @ApiOperation("刷新token")
    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @ApiOperation(value = "强制退出",httpMethod = "DELETE")
    @DeleteMapping("/online/{tokenId}")
    public edu.wit.common.result.R forceLogout(@PathVariable String tokenId) {
        redisService.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
        return edu.wit.common.result.R.ok();
    }

    @ApiOperation(value = "统计在线用户", httpMethod = "GET")
    @GetMapping("/online/list")
    public TableDataInfo list(String ipaddr, String userName) {
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
        for (String key : keys) {
            LoginUser user = redisService.getCacheObject(key);
            if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) {
                if (user.getIpaddr().contains(ipaddr) && StringUtils.equals(userName, user.getUsername())) {
                    userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
                }
            } else if (StringUtils.isNotEmpty(ipaddr)) {
                if (user.getIpaddr().contains(ipaddr)) {
                    userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
                }
            } else if (StringUtils.isNotEmpty(userName)) {
                if (StringUtils.equals(userName, user.getUsername())) {
                    userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
                }
            } else {
                userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
            }
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));

        userOnlineList.sort((t1,t2) -> t2.getLoginTime().compareTo(t1.getLoginTime()));

        return getDataTable(userOnlineList);
    }
}
